var longestCommonSubsequence = function(text1, text2) {
  const [m, n] = [text1.length, text2.length];
  let ans = 0;

  if (m === 0 || n === 0) {
    return ans;
  }

  // 长度为[0, i - 1]的字符串text1与长度为[0, j - 1]的字符串text2的最长公共子序列为dp[i][j] --- 因为不用连续，所以不需要以它为结尾
  const dp = new Array(m+1).fill(0).map(() => new Array(n+1).fill(0));

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (text1[i-1] === text2[j-1]) {
        dp[i][j] = 1 + dp[i - 1][j - 1];
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
      }
    }
  }

  ans = dp[m][n];

  return ans;

};

const text1 = "abcde", text2 = "ace" 
console.log(longestCommonSubsequence(text1, text2)) // Output: 3